package cloud.pangui.core.utils;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Auther hepangui
 * @Date 2020/11/5 0005
 */
public class PropertiesUtils {
	private static final String CHARSET_DEFAULT = "UTF-8";

	/**
	 * 读取配置文件
	 * 默认字符集UTF-8
	 *
	 * @param filePath 文件路径
	 */
	public static Properties read(String filePath) {
		return read(filePath, CHARSET_DEFAULT);
	}

	/**
	 * 读取配置文件
	 * 默认字符集UTF-8
	 *
	 * @param file 文件
	 */
	public static Properties read(File file) {
		return read(file, CHARSET_DEFAULT);
	}

	/**
	 * 读取配置文件
	 * 默认字符集UTF-8
	 *
	 * @param is 输入流
	 */
	public static Properties read(InputStream is) {
		return read(is, CHARSET_DEFAULT);
	}

	/**
	 * 读取配置文件
	 *
	 * @param filePath 文件路径
	 */
	public static Properties read(String filePath, String charset) {
		return read(new File(filePath), charset);
	}


	/**
	 * 读取配置文件
	 *
	 * @param file 文件
	 */
	public static Properties read(File file, String charset) {
		Properties props = new Properties();
		InputStreamReader in = null;
		try {
			in = new InputStreamReader(new FileInputStream(file), charset);
			props.load(in);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return props;
	}

	/**
	 * 读取配置文件
	 *
	 * @param is 输入流
	 */
	public static Properties read(InputStream is, String charset) {
		Properties props = new Properties();
		try {
			InputStreamReader in = new InputStreamReader(is, charset);
			props.load(in);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return props;
	}

	/**
	 * 写入配置文件
	 *
	 * @param filePath
	 * @param parameterName
	 * @param parameterValue
	 */
	public static void write(String filePath, String parameterName, String parameterValue) {
		Properties prop = new Properties();
		try {
			OutputStream fos = new FileOutputStream(filePath);
			InputStream fis = new FileInputStream(filePath);
			prop.load(fis);
			prop.setProperty(parameterName, parameterValue);
			prop.store(fos, "");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * toMap
	 *
	 * @param props
	 */
	public static Map toMap(Properties props) {
		Map m = new HashMap();
		Enumeration names = props.propertyNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			m.put(name, props.get(name));
		}
		return m;
	}

	/**
	 * 合并
	 *
	 * @param dest      目标
	 * @param src       源
	 * @param overwrite 覆盖
	 */
	public static void merge(Properties dest, Map<String, String> src, boolean overwrite) {
		for (String key : src.keySet()) {
			if (dest.containsKey(key) && !overwrite) {
				continue;
			}
			String value = StringUtils.emptyToDefault(src.get(key), "");
			dest.put(key, value);
		}
	}
}
